package org.jchains.receiver.gui;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintWriter;
import java.util.regex.PatternSyntaxException;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ProgressMonitor;
import javax.swing.RowFilter;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

import org.jchains.CORBA.PermissionTransferPackage.EnvironmentEntry;
import org.jchains.internal.Util;
import org.jchains.receiver.PolicyFile;

public class GUIManagement implements ActionListener {
	private ReceiverForm frm_rf;

	PolicyFile pf = new PolicyFile("", new EnvironmentEntry[] {});
	ProgressMonitor progressMonitor;
	UpdateTask task;
	JButton jb1;
	JButton jb2;
	DefaultTableModel dtm;
	EnvironmentEntry[] pe;
	JTextField tf;
	JTextField status;
	JComboBox cboSelectFilterColumn;

	public ReceiverForm getReceiverForm() {
		return frm_rf;
	}

	// class PushButtonActionListener implements ActionListener {

	public void actionPerformed(ActionEvent ae) {
		System.out.println(ae);
		if (ae.getSource() == jb1) {
			JFileChooser fc = new JFileChooser(".");
			// In response to a button click:
			int returnVal = fc.showOpenDialog(frm_rf);
			File f = null;

			if (returnVal == JFileChooser.APPROVE_OPTION) {
				f = fc.getSelectedFile();
				// This is where a real application would open the file.
				System.out.println("Opening: " + f.getName() + ".");
			} else {
				f = new File(System.getProperty("org.jchains.file",
				"permissions.csv"));
				System.out.println("Open command cancelled by user.");
			}

			progressMonitor = new ProgressMonitor(frm_rf,
					"Importing Permissions", "", 0, 100);
			progressMonitor.setProgress(0);
			task = new UpdateTask(frm_rf, progressMonitor, f,jb1, pf);

			task.execute();
			jb1.setEnabled(false);
		} else {
			String t = pf.getContent(false);
			getReceiverForm().getFieldTxtPolicyFile().setText(t);
		}

	}

	private void newFilter(TableRowSorter<PermTableModel> trs) {
		RowFilter<PermTableModel, Object> rf = null;
		try {
			rf = RowFilter.regexFilter(tf.getText());
		} catch (PatternSyntaxException e) {
			System.out.println("error with pattern:" + tf.getText());
			return;
		}
		trs.setRowFilter(rf);
	}

	public void initGUI(EnvironmentEntry[] _pe) {

		pe = _pe;
		try {
			UIManager.setLookAndFeel(UIManager
					.getCrossPlatformLookAndFeelClassName());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			e.printStackTrace();
		}
		frm_rf = new ReceiverForm();
		frm_rf.setTitle("jChains Receiver");
		frm_rf.getTxtAbout().setText(
				"jChains v1.70 written by Marc Schoenefeld \r\n"
						+ "see www.jchains.org for news");
		frm_rf.requestFocus();
		frm_rf.getFieldTxtMode().setText("started");

		final TableRowSorter<PermTableModel> trs = frm_rf.tbPermissions
				.getSorter();
		JPanel jp = new JPanel(new SpringLayout());

		jb1 = new JButton("Import file");
		frm_rf.add(jp);
		jp.add(jb1);

		cboSelectFilterColumn = new JComboBox(PermTableModel.getColumnNames());
		cboSelectFilterColumn.setSelectedIndex(frm_rf.tbPermissions
				.getFilterColumn());
		cboSelectFilterColumn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				frm_rf.tbPermissions.setFilterColumn(cboSelectFilterColumn
						.getSelectedIndex());
			}
		});

		jp.add(cboSelectFilterColumn);

		tf = new JTextField();
		tf.getDocument().addDocumentListener(new DocumentListener() {

			@Override
			public void changedUpdate(DocumentEvent arg0) {
				// TODO Auto-generated method stub
				frm_rf.tbPermissions.setFilter(tf.getText());
				// System.out.println("filter set:"+tf);
			}

			@Override
			public void insertUpdate(DocumentEvent arg0) {
				// TODO Auto-generated method stub
				frm_rf.tbPermissions.setFilter(tf.getText());
				// System.out.println("filter set:"+tf);
			}

			@Override
			public void removeUpdate(DocumentEvent arg0) {
				// TODO Auto-generated method stub
				frm_rf.tbPermissions.setFilter(tf.getText());
				// System.out.println("filter set:"+tf);
			}

		});

		jp.add(tf);

		/*
		 * JLabel jl = new JLabel("Status:",SwingConstants.TRAILING);
		 * jp.add(jl);
		 * 
		 * status = new JTextField(); jl.setLabelFor(status); jp.add(status);
		 */
		jb2 = new JButton("Gen Policy");
		jp.add(jb2);
		jb2.addActionListener(this);
		Util.makeCompactGrid(jp, 4, 1, 6, 6, 6, 6);
		jb1.addActionListener(this);

		try {
			dtm = new DefaultTableModel(new String[] { "Key", "Value" }, 0);

			// frm_rf.tbEnvironment.setModel(new EnvTableModel());
			JTable t = new JTable();
			t.setModel(dtm);
			frm_rf.setTabEnvironment(t);
			// frm_rf.tbEnvironment.setModel(dtm);

		} catch (Exception e) {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			PrintWriter pw = new PrintWriter(bos, true);
			e.printStackTrace(pw);
			frm_rf.getFieldTxtPolicyFile().setText(bos.toString());
			System.out.println(bos.toString());
		}

		// frm_rf.tbEnvironment.setTableHeader(new JTableHeader());
		// frm_rf.tbPermissions.setTableHeader(new JTableHeader());

		// TTHeader theader = new TTHeader(frm_rf.getTabPermission()
		// .getColumnModel());

		// frm_rf.getTabPermission().setTableHeader(theader);

		// frm_rf.tbEnvironment.setLayout(new MyLayoutManager());

		setResizeOn(frm_rf.getTabEnvironment());
		// setResizeOn(frm_rf.tbPermissions);
		// frm_rf.tbPermissions.setAutoResizeMode(-1);

		setEnvTable(dtm, pe);
		frm_rf.setSize(1024, 600);
		frm_rf.setLocationRelativeTo(null);
		// frm_rf.show();

		System.out.println("Gui inited!");
	}

	private void setEnvTable(DefaultTableModel dtm, EnvironmentEntry[] mee) {
		for (int i = 0; i < mee.length; i++) {
			dtm.addRow(new Object[] { mee[i].theKey, mee[i].theValue });
		}
	}

	private void setResizeOn(JTable jt) {
		// jt.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
		jt.getTableHeader().setResizingAllowed(true);
		jt.setPreferredScrollableViewportSize(new Dimension(900, 70));
		if (false) {
			jt.addMouseListener(new DebugMouseAdapter(jt));
		}
	}

}